/**
 * Taro函数重定义
 */
import Taro from '@tarojs/taro';

async function getLocationH5({ success, fail, timeout, showToast = false, ...rest }) {
  if (showToast) {
    Taro.showLoading({ title: '获取定位中' });
  }

  return new Promise((resolve, reject) => {
    navigator.geolocation.getCurrentPosition(resolve, reject, { timeout, ...rest });

    if (timeout) {
      setTimeout(reject, timeout);
    }
  })
    .then((data) => {
      const { coords } = data ?? {};

      success(coords);
      return coords;
    })
    .catch((error) => {
      fail(error);

      throw error;
    })
    .finally(() => {
      if (showToast) {
        Taro.hideLoading();
      }
    });
}

function remountGetLocation() {
  Taro.getLoc = process.env.TARO_ENV === 'h5' ? getLocationH5 : Taro.getLocation;
}

export const reMount = () => {
  remountGetLocation();
};
